package com.lancoo.ccas52.exception;


import cn.hutool.core.util.ObjUtil;
import com.lancoo.ccas52.util.EnumResultCode;
import com.lancoo.ccas52.util.ResponseObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author quin
 * @ClassName GlobalExceptionHandler.java
 * @Description 全局异常处理
 * @createTime 2022年05月19日 14:10:00
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public ResponseObject bizExceptionHandler(HttpServletRequest req, BizException e) {
        log.error("【internal server error,requestURI:{},e is :{}】", req.getRequestURI(), e);
        if (ObjUtil.isNull(e.getErrorCode())) {
            e.setErrorCode(EnumResultCode.FAIL.getCode());
        }
        e.printStackTrace();
        return ResponseObject.ofFail(e.getErrorCode(), e.getErrorMsg());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseObject validHandler(HttpServletRequest req, MethodArgumentNotValidException e) {
        log.error("【internal server error,requestURI:{},e is :{}】", req.getRequestURI(), e);
        e.printStackTrace();
        return ResponseObject.ofFail(EnumResultCode.PARAMS_ERROR, e.getFieldError().getDefaultMessage());
    }

    /**
     * 处理空指针的异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ResponseObject exceptionHandler(HttpServletRequest req, NullPointerException e) {
        log.error("【internal server error,requestURI:{},e is :{}】", req.getRequestURI(), e);
        e.printStackTrace();
        return ResponseObject.ofFail(2, "NullPointerException", e.getMessage());
    }

    /**
     * 处理404的异常
     *
     * @return
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    public ResponseObject noHandlerFoundException(HttpServletRequest req, Exception e) {
        log.error("【internal server error,requestURI:{},e is :{}】", req.getRequestURI(), e);
        e.printStackTrace();
        return ResponseObject.ofFail(2, "NoHandlerFoundException", e.getMessage());
    }

    /**
     * 处理其他异常，服务器内部错误
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseObject exceptionHandler(HttpServletRequest req, Exception e) {
        log.error("【internal server error,requestURI:{},e is :{}】", req.getRequestURI(), e);
        e.printStackTrace();
        return ResponseObject.ofFail(EnumResultCode.FAIL, e.getMessage());
    }

}
